#!/usr/bin/env python
# encoding: utf-8
'''
@author: Justin Ruan
@license: 
@contact: ruanjun@whut.edu.cn
@time: 2019-12-25
@desc:
'''

import nltk
from stanfordcorenlp import StanfordCoreNLP
import util
import os, csv
import numpy as np

# ROOT :	要处理文本的语句
# IP   :	简单从句
# NP   :	名词短语
# VP   :	动词短语
# PU   :	断句符，通常是句号、问号、感叹号等标点符号
# LCP  :	方位词短语
# PP   :	介词短语
# CP   :	由‘的’构成的表示修饰性关系的短语
# DNP  :	由‘的’构成的表示所属关系的短语
# ADVP :	副词短语
# ADJP :	形容词短语
# DP   :	限定词短语
# QP   :	量词短语
# NN   :	常用名词
# NT   :	时间名词
# PN   :	代词
# VV   :	动词
# VC   :	是
# CC   :	表示连词
# VE   :	有
# VA   :	表语形容词
# VRD  :	动补复合词
# CD   :	 表示基数词
# DT   :	 determiner 表示限定词
# EX   :	 existential there 存在句
# FW   :	 foreign word 外来词
# IN   :	 preposition or conjunction, subordinating 介词或从属连词
# JJ   :	 adjective or numeral, ordinal 形容词或序数词
# JJR  :	 adjective, comparative 形容词比较级
# JJS  :	 adjective, superlative 形容词最高级
# LS   :	 list item marker 列表标识
# MD   :	 modal auxiliary 情态助动词
# PDT  :	 pre-determiner 前位限定词
# POS  :	 genitive marker 所有格标记
# PRP  :	 pronoun, personal 人称代词
# RB   :	 adverb 副词
# RBR  :	 adverb, comparative 副词比较级
# RBS  :	 adverb, superlative 副词最高级
# RP   :	 particle 小品词
# SYM  :	 symbol 符号
# TO   :	”to” as preposition or infinitive marker 作为介词或不定式标记
# WDT  :	 WH-determiner WH限定词
# WP   :	 WH-pronoun WH代词
# WP$  :	 WH-pronoun, possessive WH所有格代词
# WRB  :	Wh-adverb WH副词
# CLP   Classifier phrase 量词短语


PROJECT_ROOT = util.get_project_root()


class NLP_Parser(object):
    def __init__(self):
        self.root_path = PROJECT_ROOT + "//data//"
        self.nlp_sdk_path = "D://Backup//nlp//stanford//stanford-corenlp-full-2018-10-05//"

    def process(self, record_filename, start, end):
        nlp = StanfordCoreNLP(self.nlp_sdk_path, lang='zh')
        file_path = "{}//data//{}".format(PROJECT_ROOT, record_filename)

        csv_file = csv.reader(open(file_path, 'r', encoding='utf-8'))
        # 性别,年龄,住院号,科室,登记日期,诊断结果
        count = 1
        results = {}
        for item in csv_file:
            if end >= count >= start:
                text = item[5]
                print(count, text)

                results[count] = (nlp.pos_tag(text), nlp.parse(text))
            elif count > end + 1:
                break
            count += 1
        return results

    def save(self, results):
        s = list(results.keys())
        m = np.min(s)
        n = np.max(s)
        filename = "{}//results//nlp_parse_{:d}_{:d}.npz".format(PROJECT_ROOT, m, n)
        np.savez_compressed(filename, results=results)

    def draw(self, filename, record_id):
        data_path = "{}//results//{}".format(PROJECT_ROOT, filename)
        data = np.load(data_path, allow_pickle=True)
        results = data["results"].item()

        record = results[record_id][1]
        record = record.replace("(PU ()", "(PU （)").replace("(PU ))", "(PU ）)")
        tree = nltk.Tree.fromstring(record)
        print(results[record_id][0])
        tree.draw()
